<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="状态" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.status=='0'" class="revoke_space">
                <svg-icon icon-class="草稿" />
                <span>草{{ '\xa0\xa0\xa0' }}稿</span>
              </div>
              <div v-if="scope.row.status=='2' ||scope.row.status=='1' " class="insufficient_space2">
                <svg-icon icon-class="不足" />
                <span>审批中</span>
              </div>
              <div v-if="scope.row.status=='3'" class="insufficient_space">
                <svg-icon icon-class="驳回" />
                <span>已驳回</span>
              </div>
              <div v-if="scope.row.status=='4'" class="adequate_space">
                <svg-icon icon-class="通过" />
                <span>已通过</span>
              </div>
              <div v-if="scope.row.status=='5'" class="under_execution">
                <svg-icon icon-class="执行中" />
                <span>执行中</span>
              </div>
              <div v-if="scope.row.status=='6'" class="adequate_space">
                <svg-icon icon-class="通过" />
                <span>已完成</span>
              </div>
              <div v-if="scope.row.status=='7'" class="revoke_space">
                <svg-icon icon-class="撤销" />
                <span>已关闭</span>
              </div>
            </template>
          </el-table-column>
          <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :min-width="column.minWidth" :width="column.width" :align="column.align" />
          <el-table-column
            label="附件"
            min-width="80"
          >
            <template slot-scope="scope">
              <FileManage
                :file-names="scope.row.fileName"
                :file-real-names="scope.row.fileRealName"
                :file-urls="scope.row.url"
                :readonly="true"
                class="accessory"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status==0||scope.row.status==3"
                v-hasPermi="['sale:order:edit']"
                type="text"
                @click.stop="edit(scope.row)"
              >编辑</el-button>
              <span v-else class="el-button--text button_grey">编辑</span>
              <el-button
                v-if="scope.row.canDelete ==1"
                v-hasPermi="['sale:order:delete']"
                type="text"
                @click.stop="deleteOne(scope.row)"
              >删除</el-button>
              <span v-else class="el-button--text button_grey">删除</span>
              <!-- <span v-else class="el-button--text button_grey">完结</span> -->
              <el-button
                v-if="scope.row.status ==4 || scope.row.status ==5"
                v-hasPermi="['sale:order:finish']"
                type="text"
                @click.stop="finishOrder(scope.row)"
              >关闭</el-button>
              <span v-else class="el-button--text button_grey">关闭</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { list, remove, getInfo, finishOrder } from '@/api/saleManage/saleOrder'
import { getDictSelects } from '@/api/common/common'
import AddOrUpdate from './addOrUpdate' // 新增或编辑页面
import { mapGetters } from 'vuex'
import chooseFinishOrder from './chooseFinishOrder.vue'
import ShowDetail from './showDetail.vue' // 查看页面
import ShowMaterialDetail from './showMaterialDetail.vue' // 查看页面
export default {
  data() {
    return {
      loading: true,
      pageId: '销售订单', // 页面唯一标识
      pageExportId: '销售订单导出', // 页面导出标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      // tableKey: 1,
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        // { prop: 'statusName', label: '状态', canOrder: false },
        { prop: 'code', label: '销售订单号' },
        { prop: 'orderName', label: '销售人员', canOrder: false },
        // { prop: 'orderTime', label: '制单日期' },
        { prop: 'orderTypeLabel', label: '订单类型', canOrder: false },
        { prop: 'saleOrderPercent', label: '发货比例(%)' },
        { prop: 'newMaterialName', label: '物料明细', canOrder: false },
        { prop: 'customerName', label: '客户名称', canOrder: false },
        { prop: 'orderGoodsTime', label: '订货日期' },
        { prop: 'contractCode', label: '合同号', canOrder: false },
        { prop: 'allPriceThousandths', label: '未税总金额', minWidth: this.SETTINGS.settings_decimalDigits_length, align: 'right' },
        { prop: 'taxAllPriceThousandths', label: '含税总金额', minWidth: this.SETTINGS.settings_decimalDigits_length, align: 'right' },
        { prop: 'taxThousandths', label: '税额', minWidth: this.SETTINGS.settings_decimalDigits_length, align: 'right' },
        { prop: 'remark', label: '备注', canOrder: false }

      ],
      exportTableColumns: [// 表格常规字段（初始值）
        { prop: 'statusName', label: '状态' },
        { prop: 'code', label: '销售订单号' },
        { prop: 'orderName', label: '销售人员', canOrder: false },
        { prop: 'orderTypeLabel', label: '订单类型', canOrder: false },
        { prop: 'saleOrderPercent', label: '发货比例(%)' },
        { prop: 'newMaterialName', label: '物料明细', canOrder: false },
        { prop: 'customerName', label: '客户名称', canOrder: false },
        { prop: 'orderGoodsTime', label: '订货日期' },
        { prop: 'contractCode', label: '合同号', canOrder: false },
        { prop: 'allPrice', label: '未税总金额', minWidth: this.SETTINGS.settings_decimalDigits_length, align: 'right' },
        { prop: 'taxAllPrice', label: '含税总金额', minWidth: this.SETTINGS.settings_decimalDigits_length, align: 'right' },
        { prop: 'tax', label: '税额', minWidth: this.SETTINGS.settings_decimalDigits_length, align: 'right' },
        { prop: 'remark', label: '备注', canOrder: false }
      ],
      defaultExport: [],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'code', label: '销售订单号', type: 'input' },
        { prop: 'customerName', label: '客户名称', type: 'input' },
        { prop: 'orderGoodsTime', label: '订货日期', type: 'time', isTime: true },
        { prop: 'statusList', label: '状态', type: 'select-multiple', optionsName: 'statusOptions' }, // select-multiple：多选
        { prop: 'orderName', label: '销售人员', type: 'input' },
        // { prop: 'orderTime', label: '制单日期', type: 'time', isTime: true },
        { prop: 'orderTypeCode', label: '订单类型', type: 'dict', optionsName: 'OrderTypeCodeOptions' },
        { prop: 'contractCode', label: '合同号', type: 'input' }
        // { prop: 'allPrice', label: '未税总金额', type: 'input' },
        // { prop: 'taxAllPrice', label: '含税总金额', type: 'input' },
        // { prop: 'tax', label: '税额', type: 'input' }
      ],
      operationData: [ // 右上角的操作按钮
        { label: '新增', perm: 'sale:order:add' },
        { label: '打印', perm: '' },
        { label: '批量删除', perm: 'sale:order:delete' },
        { label: '批量导出3', perm: 'sale:order:export' },
        { label: '页面配置', perm: '' }
      ],
      reportLists: [],
      statusOptions: [ // 选择组件数据源
        { value: '0', label: '草稿' },
        // { value: '1', label: '待审批' },
        { value: '2', label: '审批中' },
        { value: '3', label: '已驳回' },
        { value: '4', label: '已通过' },
        { value: '5', label: '执行中' },
        { value: '6', label: '已完成' },
        { value: '7', label: '已关闭' }
      ],
      OrderTypeCodeOptions: [],
      showKey: [
        {
          name: '基本信息',
          columns: [
            { type: 'form', name: '销售订单号', key: 'code' },
            { type: 'form', name: '销售人员', key: 'orderName' },
            { type: 'form', name: '制单日期', key: 'orderTime' },
            { type: 'form', name: '订单类型', key: 'orderTypeLabel' },
            { type: 'form', name: '客户名称', key: 'customerName' },
            { type: 'form', name: '订货日期', key: 'orderGoodsTime' },
            { type: 'form', name: '合同号', key: 'contractCode' },
            { type: 'form', name: '未税总金额', key: 'allPriceThousandths' },
            { type: 'form', name: '含税总金额', key: 'taxAllPriceThousandths' },
            { type: 'form', name: '税额', key: 'taxThousandths' },
            { type: 'file', name: '附件', fileName: 'fileName', fileRealName: 'fileRealName', fileUrl: 'url' },
            { type: 'form', name: '备注', key: 'remark', length: 'double' },
            {
              type: 'table', name: '', key: 'data'
            },
            { type: 'print', name: '打印记录', key: '' }
          ]
        },
        {
          name: '客户信息',
          columns: [
            // { type: 'formData', name: '计税方式', key: 'taxTypeLabel' },
            // { type: 'formData', name: '税率%', key: 'taxRateLabel' },
            // { type: 'formData', name: '结算方式', key: 'settlementTypeLabel' },
            // { type: 'formData', name: '结算币别', key: 'settlementCurrencyLabel' },
            { type: 'formData2', name: '交货方式', key: 'deliveryTypeLabel' },
            { type: 'formData2', name: '联系人', key: 'consignee' },
            { type: 'formData2', name: '联系方式', key: 'phone' },
            { type: 'formData2', name: '注意事项', key: 'attentionMatters' },
            { type: 'formData2', name: '收货地址', key: 'deliveryAddress', length: 'double' }
          ]
        },
        {
          name: '审批详情',
          columns: [
            { type: 'review', name: '评审进度', key: 'taskList' }
          ]
        }
      ],
      showKey2:
        {
          name: '基本信息',
          columns: [
            { type: 'form', name: '销售订单号', key: 'code' },
            {
              type: 'table', name: '', key: 'data'
            }
          ]
        }

    }
  },
  watch: {
    notificationId(newValue, oldValue) {
      if (newValue !== oldValue && newValue !== 0 && this.$store.state.notification.notificationStatus == '1') {
        const rowId = { id: this.notificationId }
        this.showDetail(rowId)
      }
    }
  },
  created() {
    this.getDictOptions()
    if (this.$store.state.order.contendId) {
      this.showDetail({ id: this.$store.state.order.contendId })
      this.$store.state.order.contendId = ''
    }
  },
  computed: {
    ...mapGetters([
      'notificationId', 'userName'
    ])
  },
  mounted() {
    if (this.notificationId !== 0) {
      const rowId = { id: this.notificationId }
      if (this.$store.state.notification.notificationStatus == '1') {
        this.showDetail(rowId)
      }
    }
  },
  methods: {
    cellStyle({ row, column }) {
      if (column.property == 'code' || column.property == 'newMaterialName') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'code':
          this.showDetail(row)
          break
        case 'newMaterialName':
          this.showMaterialDetail(row)
          break
      }
    },
    showDetail(row) {
      getInfo(row[this.mainId]).then(res => {
        if (res.data.status != 0 && res.data.isApprovalShow != 1 && res.data.taskList.length > 0) {
          const obj = {
            taskNoName: '审批结束',
            taskList: []
          }
          if (res.data.taskList.length > 0) {
            if (res.data.taskList[res.data.taskList.length - 1].approvalStatus == 3 || res.data.taskList[res.data.taskList.length - 1].approvalStatus == 4) {
              obj.approvalStatus = 5
            } else {
              obj.approvalStatus = 0
            }
          }
          res.data.taskList.push(obj)
        }
        this.$layer.iframe({// 弹框
          content: {
            content: ShowDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: res.data,
              businessId: row[this.mainId],
              showKey: this.showKey,
              isSaleOrder: true
            }// props
          },
          area: ['1320px', '800px'],
          title: '查看销售订单', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
      this.$store.dispatch('notification/changeId', 0)
    },
    showMaterialDetail(row) {
      getInfo(row.id).then(res => {
        this.$layer.iframe({// 弹框
          content: {
            content: ShowMaterialDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: res.data,
              showKey: this.showKey2
            }// props
          },
          area: ['1320px', '800px'],
          title: '查看物料明细', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
    },
    finishOrder(row) {
      const _this = this
      this.$confirm('确定要关闭吗', '关闭确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        finishOrder(row[_this.mainId]).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.selectionsAll = []
          _this.getList()
        })
      }).catch(() => {})
    },
    getDictOptions() {
      getDictSelects('orderTypeCode').then(res => {
        this.OrderTypeCodeOptions = res.data
      })
    },
    getExportData(data) {
      return list(data)
    },
    refresh() {
      this.pageData.pageNum = 1
      this.getList()
    },
    refresh2() {
      this.tableData = []
      setTimeout(() => {
        this.getList()
      }, 50)
    },
    getList() {
      list(this.pageData).then(res => {
        this.tableData = res.data
        this.total = res.total
        this.loading = false
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
        })
      })
    },
    add() {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['1320px', '800px'],
        title: '新增销售订单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    edit(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          }// props
        },
        area: ['1320px', '800px'],
        title: '编辑销售订单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    finish(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseFinishOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          }// props
        },
        area: ['1200px', '800px'],
        title: '完结销售订单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        remove(row[_this.mainId]).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.selectionsAll = []
          _this.getList()
        })
      }).catch(() => {})
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove(deleteIds)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-table__row{
  height: 44px;
}
.accessory {
  color: #387bfc
}
.under_execution{
  color: rgb(17,109,252);
  background-color:rgb(230, 243, 255) ;
  border-radius: 3px;
  padding: 3px 0;
  width: 80px;
  text-align: center;
}
.adequate_space{
  color: #19BE6B;
  background-color:rgb(223, 249, 241) ;
  border-radius: 3px;
  padding: 3px 0;
  width: 80px;
  text-align: center;
}
.insufficient_space{
  color: rgb(231,108,108);
  background-color:rgb(255,238,238) ;
  border-radius: 3px;
  padding: 3px 0;
  width: 80px;
  text-align: center;
}
.insufficient_space2{
  color: rgb(255,151,32);
  background-color:rgb(255,245,239) ;
  border-radius: 3px;
  padding: 3px 0;
  width: 80px;
  text-align: center;
}
.revoke_space{
  color: #999999;
  background-color:rgb(242,242,242) ;
  border-radius: 3px;
  padding: 3px 0;
  width: 80px;
  text-align: center;
}
</style>
